<template>
  <div class="userlist">
    <!-- 头部搜索 -->
      <header>
      <span>
        <span>账号检索</span>
        <el-input v-model="user" placeholder="请输入关键字" style="width:200px"></el-input>
      </span>
      <span>
        <span>日期检索</span>
        <el-select v-model="date" placeholder="全部">
          <el-option v-for="item in timeOption" :key="item.key" :label="item.type" :value="item.key"></el-option>
        </el-select>
      </span>
      <span>
        <span></span>
          <el-date-picker v-model="value1" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
      </span>

      <p>
       <el-link type="primary"  @click="dialogTableVisible = true"  style="margin-left:8px" class="border_h">添加账号</el-link>
        <el-button type="primary" icon="el-icon-search" style="float: right;" @click="searchAll" >搜索</el-button>
      </p>
    </header>

    <div class="tableList">
    <!-- 表格 -->
      <el-table  :data="userList.slice((currentPage-1)*pageSize,currentPage*pageSize)" style="width:100%;margin-left:8px" 
      :header-cell-style="{background:'#EBEEF5'}"
      >
      <el-table-column prop="name" label="用户账号">
        <template slot-scope="scope">{{scope.row.username}}</template>
      </el-table-column>
      <el-table-column prop="name" label="用户姓名">
        <template slot-scope="scope">{{scope.row.name?scope.row.name:'---'}}</template>
      </el-table-column>
       <el-table-column prop="date" label="是否为初始密码" >
          <template slot-scope="scope">{{scope.row.password==='123456'?'是':'否'}}</template>
      </el-table-column>
       <el-table-column prop="date" label="最近登录日期" >
        <template slot-scope="scope">{{$getDate(Number(scope.row.lastlogin))}}</template>
      </el-table-column>
      <el-table-column prop="date" label="创建时间" >
        <template slot-scope="scope">{{$getDate(Number(scope.row.createtime))}}</template>
      </el-table-column>
      <el-table-column prop="date" label="操作" >
         <template slot-scope="scope">
            <el-button type="text" @click="editUser(scope.row)" style="color:orange">{{scope.row.username!=='admin'?'编辑':null}}</el-button>
            <el-button type="text" @click="Black(scope.row.username,'冻结',scope.row.userid)" >{{scope.row.username!=='admin'?'冻结':null}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="pagination_m">
       <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,6,8]" 
          :page-size="pageSize"        
          layout="total, sizes, prev, pager, next, jumper"
          :total="userList.length">   
      </el-pagination>
    </div>
     <!-- 添加账号 -->
    <div>
      <el-dialog title="添加账号" :visible.sync="dialogTableVisible" id="dialog">
        <div class="">
            <div class="iptDives">
              <span class="edituser_span">账号:</span><el-input placeholder="请输入账号" prefix-icon="el-icon-user" v-model="newuser"/>
            </div>
            <div class="iptDives">
              <span style="width:120px;color:grey">密码:</span><div>{{newpwd}}</div>
            </div>
             <div class="iptDives">
              <span class="edituser_span">姓名:</span><el-input placeholder="请输入姓名"  v-model="newname"/>
            </div>
             <div class="iptDives">
              <span class="edituser_span">年龄:</span><el-input placeholder="请输入年龄"  v-model="newage"/>
               </div>
               <div class="iptDives">
              <span class="edituser_span">手机:</span><el-input placeholder="请输入手机号"  v-model="newphone"/>
            </div>
            <div class="iptDives">
              <span style="width:118px;color:grey">性别:</span>
              <el-select v-model="newsex" placeholder="请选择性别" >
                <el-option
                  v-for="item in sexOption"
                  :key="item.key"
                  :label="item.sex"
                  :value="item.sex">
                </el-option>
              </el-select>
            </div>
            <div class="iptDives">
              <span class="edituser_span">地址:</span><el-input placeholder="请输入地址"  v-model="newaddress" />
            </div>
            <div class="iptDives">
              <span style="width:122px;color:grey">必选:</span>
              <el-radio v-model="newType" label="讲师" style="padding: 8px 0">讲师</el-radio>
              <el-radio v-model="newType" label="辅导员" style="padding: 8px 0">辅导员</el-radio>
            </div>
             <div class="iptDives">
              <span style="width:118px;color:grey">角色:</span>
              <el-select v-model="value" placeholder="请选择" >
                <el-option
                  v-for="item in roleOption"
                  :key="item.roleid"
                  :label="item.role"
                  :value="item.roleid">
                </el-option>
              </el-select>
            </div>
            <div class="btnDiv">
                 <el-button  type="primary" @click="dialogTableVisible = false;value='';newuser='';newname='';newsex='';newaddress='';newage='';newphone='';newType=''">取消</el-button>
                 <el-button  type="primary" @click="addUser">添加</el-button>
            </div>
        </div>
      </el-dialog>
    </div>
        <!-- 编辑账号 -->
    <div>
      <el-dialog title="编辑账号" :visible.sync="EditTableVisible" id="editdialog">
        <div class="">
            <div class="iptDives">
              <span class="edituser_span">账号:</span><div>{{edituser}}</div>
            </div>
            <div class="iptDives">
              <span class="edituser_span">密码:</span><div style="width:140px" >{{editpwd}}</div>
              <el-button  type="primary" @click="resetPwd">重置密码</el-button>
            </div>
            <div class="iptDives">
              <span class="edituser_span">状态:</span>
              <el-radio v-model="radio" label="1">启用</el-radio>
              <el-radio v-model="radio" label="2">禁用</el-radio>
            </div>      
             <div class="iptDives">
              <span style="width:149px;color:grey">角色:</span>
              <el-select v-model="editrole" placeholder="请选择" >
                <el-option
                  v-for="item in roleOption"
                  :key="item.roleid"
                  :label="item.role"
                  :value="item.roleid">
                </el-option>
              </el-select>
            </div>
            <div class="btnDiv">
                 <el-button  type="primary" @click="EditTableVisible = false">取消</el-button>
                 <el-button  type="primary" @click="sureEdit">确定</el-button>
            </div>
        </div>
    </el-dialog>
    </div>
    
    </div>
  </div>
</template>

<script>
import md5 from 'md5'
  export default {
    data() {
      return {
        value1: '',
        user:'',
        userList:[],
        date:'',
        options:[],
        pageSize:5,
        currentPage:1,
        dialogTableVisible:false,
        EditTableVisible:false,
        newuser:'',
        newpwd:'123456',
        newname:'',
        newsex:'',
        newage:'',
        newphone:'',
        newType:'讲师',
        newaddress:'',
        startTime:'',
        endTime:'',
         options: [{
          roleid: '1',
          role: '黄金糕'
        }, {
          roleid: '2',
          role: '双皮奶'
        }, {
          roleid: '3',
          role: '蚵仔煎'
        }, {
          roleid: '4',
          role: '龙须面'
        }, {
          roleid: '5',
          role: '北京烤鸭'
        }],
        value: '',
        roleOption:[],
        sexOption:[
          {
            key: 1,
            sex: '男'
          },
          {
            key: 2,
            sex: '女'
          }
        ],
        timeOption:[
          {
            key: 'createtime',
            type: '创建时间'
          },
          {
            key: 'logintime',
            type: '登录时间'
          }
        ],
        type:'',
        edituser:'',
        editpwd:'',
        editname:'',
        editsex:'',
        editage:'',
        editphone:'',
        editaddress:'',
        editid:'',
        editrole:'',
        radio: '1',
        editobj:{}
      };
    },
    mounted(){this.setList()},
    methods:{
    parseTime(str){//处理时间选择器
      var d = new Date(str); 
      let time=d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();  
      let  a= new Date(time)
          return a.getTime()
    },
    searchAll(){//多项搜索
      this.startTime = this.parseTime(this.value1[0])
      this.endTime = this.parseTime(this.value1[1])
      const {date,startTime,endTime,user,$httpAxios,$api} = this
      
      let obj = {
        username:user,
        type:date,
        starttime:startTime*1,
        endtime:endTime*1
        }
        $httpAxios($api.user_Search({obj}),res=>{
            this.userList=res.data
            this.$message.success(res.msg);
            this.currentPage = 1;
      })
    },
    resetPwd(){//修改密码
      let n=0
      let str=""
      while(n<6){
          let i=Math.floor(Math.random()*Array.from(new Array(9).keys()).length)
          str+=i
          n++
      }
      this.editpwd=str
      this.$message('密码已重置，新密码为'+str)
      
    },
    editUser(userid){//编辑展示
     this.EditTableVisible = true
     this.edituser=userid.username
     this.editpwd=userid.password
     this.editid=userid.userid
     this.editobj=userid
     let arr=this.roleOption.filter(item=>{
       return item.roleid===userid.roleid*1
     })
     this.editrole=arr[0].role
    },
    sureEdit(){//编辑确定
      const {editrole,editpwd,$api,$httpAxios,$message,radio,editid,editobj} = this
      let obj = {
          userid:editid,
          roleid:editobj.roleid+'',
          password:editpwd,
          state:radio==='2'?'freeze':'ok'
      }
      $httpAxios($api.user_Edit({obj}),res=>{
            this.$message.success(res.msg)
            this.setList()
      })
      this.EditTableVisible = false
    },
    
    addUser(){//添加用户
    const {value,newuser,newpwd,$api,$httpAxios,$message,newname,newsex,newaddress,newage,newphone,newType} = this
    if(newuser === ''||!(/^[A-Za-z0-9,.;?@]+$/.test(newuser))) return $message('请输入账号或账号名有误')
    if(newpwd === '') return $message('请输入密码')
    if(value=== '') return $message('请选择角色')
    if(!(/^(?:[1-9][0-9]?|1[01][0-9]|120)$/).test(newage)) return $message('请输入正确格式的年龄')
    if(newphone=== '') return $message('请输入手机号码')
    if(!(/^1[3456789]\d{9}$/.test(newphone))) return $message('手机号码有误，请重填')
    if(newsex=== '') return $message('请选择性别')
    if(newaddress=== '') return $message('请输入地址')
  
    let obj = {
        roleid:value+'',
        username:newuser,
        password:newpwd,
        name:newname,
        age:newage,
        phone:newphone,
        address:newaddress,
        sex:newsex,
        type:newType
    }
    $httpAxios($api.user_Add({obj}),res=>{
          this.$message.success(res.msg);  
          this.setList();
          this.currentPage = 1;
    })
    this.value='';this.newuser='';this.newname='';this.newsex='';this.newaddress='';this.newage='';this.newphone='';
    this.dialogTableVisible = false
   },
  setList(){
    this.$httpAxios(this.$api.user_List(),res=>{
          this.userList=res.data;
          this.currentPage = 1;
    })
      this.$httpAxios(this.$api.role_List(),res=>{
          this.roleOption = res.data
    })
  },
  // 分页器
  handleCurrentChange(currentPage) {
    this.currentPage = currentPage;
  },
  // 每张显示的个数
  handleSizeChange(size) {
    this.pageSize = size;
  },
  Black(username,msg,userid){
    this.$confirm(`您确定要对当前用户 ${username} 进行${msg}吗`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }) .then(() => {
          this.$httpAxios(this.$api.user_Freeze({userid}),res=>{
               this.$message.success(res.msg);  
               this.setList()
          })
      }).catch(() => {this.$message({type: 'info',message: '已取消'});});
    }
  },
    
  };
</script>

<style scoped >
header{
  padding: 8px 0px;
}
header>span>span{
  margin: 0 12px;
}
#dialog{
  width:65%;
  margin:auto
}
.edituser_span{
  width: 150px;
  color: grey;
}
.iptDives{
  display: flex;
  margin: 10px 20px;
  height: 30px;
  line-height: 30px;
}
.btnDiv{
    width:100%;
    text-align: right;
}
#editdialog{
  width: 70%;
  margin: auto;
}

</style>